import { uploadImag, createRobotAccount, bindRobotAccount } from "../../api/webApi/index.js"
import { closeUnwantedPages } from "../../utils/index.js"
export async function tk_bindAccount_main(task, browser, index, taskId, bindAccountParams) {
  console.log("tk绑定账号")
  console.log("task====>", task)
  console.log("开始执行TikTok绑定业务账号")
  try {
    let accountInfo = {
      account: "",
      nickName: "",
      avatar: "",
    }
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 10))
    await closeUnwantedPages(browser, ["www.tiktok.com"])
    const page = await browser.newPage()
    await page.setViewport({ width: 1920, height: 1080 })
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 5))
    // 导航到Threads网站
    await page.goto("https://www.tiktok.com", {
      waitUntil: "networkidle2",
    })
    // 获取主页按钮
    const profileButtonSelector = "h2:nth-child(9) .TUXButton-content"
    await page.waitForSelector(profileButtonSelector, { timeout: 10000 })
    const profileButton = await page.$(profileButtonSelector)
    console.log("个人主页按钮=====>", profileButton)
    if (profileButton) {
      // 点击搜索按钮后等待页面跳转加载
      await Promise.all([
        profileButton.click(),
        page.waitForNavigation({ waitUntil: "networkidle0" }), // 等待页面完全加载
      ])
    } else {
      console.log("按钮没有找到")
      throw new Error("找不到个人主页按钮")
    }
    // 等待账号、昵称、头像出现
    const accountDomSelector = 'h1[data-e2e="user-title"]'
    await page.waitForSelector(accountDomSelector, { timeout: 10000 })
    const accountDom = await page.$(accountDomSelector)
    // 获取账号
    const account = await page.evaluate((el) => el.textContent.trim(), accountDom)
    console.log("账号：", account)
    accountInfo.account = account
    // 获取昵称
    const userNameDomSelector = 'h2[data-e2e="user-subtitle"]'
    await page.waitForSelector(userNameDomSelector, { timeout: 10000 })
    const userNameDom = await page.$(userNameDomSelector)
    const userName = await page.evaluate((el) => el.textContent.trim(), userNameDom)
    console.log("昵称：", userName)
    accountInfo.nickName = userName
    // 获取头像的父元素
    const avatarParentSelector = 'span.e1vl87hj2'
    await page.waitForSelector(avatarParentSelector, { timeout: 10000 })
    const avatarParent = await page.$(avatarParentSelector)
    // 获取头像
    // 获取头像图片（需要根据实际页面元素调整选择器）
    const avatarElement = await avatarParent.$('img[class="css-1zpj2q-ImgAvatar e1e9er4e1"]')
    let avatarBuffer = null
    if (avatarElement) {
      const avatarSrc = await avatarElement.evaluate((img) => img.src)
      const response = await page.goto(avatarSrc)
      avatarBuffer = await response.buffer()
      accountInfo.avatar = avatarBuffer
    }
    const blob = new Blob([avatarBuffer], { type: "image/png" }, "avatar.png")

    const formData = new FormData()
    formData.append("file", blob, {
      filename: "image.png",
      contentType: "image/png",
    })

    const uploadRes = await uploadImag(formData, { headers: { "Content-Type": "multipart/form-data" } })
    console.log("上传头像返回结果：", uploadRes.data)
    accountInfo.avatar = uploadRes.data
    console.log("获取到的账号信息：", accountInfo)
    const robotAccountRes = await createRobotAccount(
      {
        platformAccount: accountInfo.account,
        nickName: accountInfo.nickName,
        avatarUrl: accountInfo.avatar,
      },
      {
        headers: {
          "X-Platform": task.platformName,
          "X-Device-Id": task.deviceId,
          "tenant-id": task.tenantId,
        },
      }
    )
    console.log("创建机器人账号返回结果：", robotAccountRes.data)
    // 绑定机器人账号
    const bindRes = await bindRobotAccount(
      {
        platformAccount: accountInfo.account,
        platformName: task.platformName,
      },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Platform": task.platformName,
          "X-Device-Id": task.deviceId,
          "tenant-id": task.tenantId,
        },
      }
    )
    console.log("绑定机器人账号返回结果：", bindRes.data)

    // 明确返回成功结果
    return {
      success: true,
      account: accountInfo.account,
      message: `账号 ${accountInfo.account} 绑定成功`,
    }
  } catch (error) {
    console.error("Tiktok绑定账号过程出错：", error)
    // 明确抛出错误，以便上层Promise可以捕获
    throw error
  }
}

